﻿using HenuAlbum.ControllerModels;
using HenuAlbum.DbContext;
using HenuAlbum.Identity;
using HenuAlbum.Models;
using HenuAlbum.ResponseModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HenuAlbum.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ResourceTagController : ControllerBase
    {
        private readonly AppDbContext _appDbContext;

        public ResourceTagController(AppDbContext appDbContext)
        {
            _appDbContext = appDbContext;

        }

        [HttpGet]
        public async Task<IActionResult> GetResourceTags()
        {
            var list = await _appDbContext.ResourceTag
                .AsNoTracking()
                .Where(x => x.ForSelection == true)
                .Select(x => new
                {
                    x.Id,
                    x.Name,
                    x.Description
                })
                .ToListAsync();
            return Ok(new ArrayResponse(list));
        }

        [Authorize(Roles = "管理员")]
        [HttpPost("Add")]
        public async Task<IActionResult> AddResourceTag(AddResourceTagParams param)
        {
            _appDbContext.ResourceTag.Add(new ResourceTag()
            {
                Name = param.Name,
                Description = param.Description,
                ForSelection = true
            });
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse());
        }

     



        [Authorize(Roles = "管理员")]
        [HttpPost("Remove")]
        public async Task<IActionResult> RemoveResourceTag(RemoveResourceTagParams param)
        {
            var item = await _appDbContext.ResourceTag.Where(x => x.Id == param.Id).FirstOrDefaultAsync();
            if (item == null)
            {
                return BadRequest(new NotExistsError("标签不存在!"));
            }
            _appDbContext.ResourceTag.Remove(item);
            await _appDbContext.SaveChangesAsync();
            return Ok(new OkResponse());
        }

    }
}
